<template>
  <!-- 中药处方 -->
  <section>
    <el-form :model="form" ref="form" label-position="top">
      <table class="table-box">
        <thead>
          <tr>
            <th>药品</th>
            <th>库存</th>
            <th>剂量</th>
            <th>单位</th>
            <th>特殊要求</th>
            <th>总量</th>
            <!-- <th>状态</th> -->
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item,index) in form.tableList" :key="index">
            <td>
              <el-tooltip :disabled="!item.sellMoney" effect="dark" :content="'￥：'+item.sellMoney" placement="right">
                <el-link :underline="false" type="primary" class="vertical-middle">{{item.drugName}}</el-link>
              </el-tooltip>
            </td>
            <td>库存： {{item.inventory.packNum}}{{item.inventory.packUnit|changeAssist(oneDoseUnitArr)}}</td>
            <td>
              <el-form-item :prop="'tableList.' + index + '.oneDose'" :rules="[rulesRequired,rulesNumber]">
                <el-input v-model.number="item.oneDose" :disabled="toDisabled(item)" type="number" style="width:70px;"></el-input>
              </el-form-item>
            </td>
            <td>
              <el-form-item :prop="'tableList.' + index + '.oneDoseUnit'" :rules="[rulesRequired]">
                <el-select disabled v-model="item.oneDoseUnit" placeholder="请选择" style="width:100px;">
                  <el-option v-for="(item,index) in oneDoseUnitArr" :key="index" :label="item.desc" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </td>
            <td>
              <el-form-item :prop="'tableList.' + index + '.remark'">
                <el-input v-model="item.remark" :disabled="toDisabled(item)"></el-input>
              </el-form-item>
            </td>
            <td>{{item.useTotal}}{{item.totalUnit|changeAssist(oneDoseUnitArr)}}</td>
            <!-- <td>待发药</td> -->
            <td>
              <el-link v-if="!toDisabled(item)" :underline="false" type="primary" @click="onDelItem(item,index)">
                <i class="el-icon-delete"></i>
              </el-link>
            </td>
          </tr>
        </tbody>
      </table>
      <br />
      <div>
        <dialogSearchDrug :patientId="patientId" :doctorId="doctorId" @addItem="addFormList" type="2"></dialogSearchDrug>
      </div>
      <br />
      <table width="100%" border="0">
        <tr>
          <td>
            <el-form-item label="用法：" prop="curePrescriptionUse.usage" :rules="[rulesRequired]">
              <el-select v-model="form.curePrescriptionUse.usage" placeholder="请选择">
                <el-option v-for="(item,index) in useArr" :key="index" :label="item.desc" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </td>
          <td>
            <el-form-item label="单次剂量：" prop="curePrescriptionUse.dailyDose" :rules="[rulesRequired,rulesNumber]">
              <el-input v-model.number="form.curePrescriptionUse.dailyDose" type="number"></el-input>
            </el-form-item>
          </td>
          <td>
            <el-form-item label="天数：" prop="curePrescriptionUse.day" :rules="[rulesRequired,rulesNumber]">
              <el-input v-model.number="form.curePrescriptionUse.day" type="number"></el-input>
            </el-form-item>
          </td>
          <td>
            <el-form-item label="总剂数：" prop="curePrescriptionUse.totalDose" :rules="[rulesRequired,rulesNumber]">
              <el-input :value="form.curePrescriptionUse.totalDose" type="number"></el-input>
            </el-form-item>
          </td>
          <td>
            <el-form-item label="频次：" prop="curePrescriptionUse.frequency" :rules="[rulesRequired]">
              <el-select v-model="form.curePrescriptionUse.frequency" placeholder="请选择">
                <el-option v-for="(item,index) in frequencyArr" :key="index" :label="item.desc" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </td>
          <td>
            <el-form-item label="取药地点：" prop="curePrescriptionUse.getAddress" :rules="[rulesRequired]">
              <el-select v-model="form.curePrescriptionUse.getAddress" placeholder="请选择">
                <el-option v-for="(item,index) in getAddressArr" :key="index" :label="item.desc" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </td>
        </tr>
      </table>
    </el-form>
    <br />
    <div class="form-tool" style="border-top:1px solid #eee;padding-top:20px;">
      <div>
        <el-button @click="onSubmit" :loading="btnLoading" type="primary">保存</el-button>
      </div>
      <div>
        <!-- <el-button @click="onSaveTemplate">
          <i class="iconfont iconcunchu vertical-middle"></i>
          <span class="vertical-middle">存为模板</span>
        </el-button> -->
        <el-button v-if="form.tableList.length>0&&templateSave.t1==false" @click="dialogTraditionPrint=true">
          <i class="iconfont icondayin vertical-middle" style="font-size:20px;"></i>
          <span class="vertical-middle">打印处方</span>
        </el-button>
      </div>
    </div>
    <!-- <dialogSaveChinaDrugTemplate v-model="dialogSaveChinaDrugTemplate" :deptId="deptId" :doctorId="doctorId" :patientId="patientId" :defaultList="form.tableList" :curePrescriptionUse="form.curePrescriptionUse"></dialogSaveChinaDrugTemplate> -->
    <dialogTraditionPrint v-model="dialogTraditionPrint" :cureId="cureId" :list="form.tableList" :useObj="form.curePrescriptionUse" :patientInfo="patientInfo" :professionalDeptName="professionalDeptName" :cureFirstVisitRecord="cureFirstVisitRecord" :doctorName="doctorName"></dialogTraditionPrint>
  </section>
</template>
<script>
import zyMixin from "../_js/zyMixin.js";
export default {
  mixins: [zyMixin],
  props: [
    "selectTemplateData",
    "cureId",
    "deptId",
    "doctorId",
    "patientId",
    "initData",
    "cureFirstVisitRecord"
  ],
  components: {
    dialogSearchDrug: () => import("./dialogSearchDrug.vue"),
    // dialogSaveChinaDrugTemplate: () =>
    //   import("./dialogSaveChinaDrugTemplate.vue"),
    dialogTraditionPrint: () => import("../../_print/dialogTraditionPrint.vue")
  },
  computed: {},
  data() {
    return {
      hpId: "",
      isOpenEdit: false,
      btnLoading: false,
      deptName: "",
      professionalDeptName: "",
      doctorName: "",
      dialogSaveChinaDrugTemplate: false,
      dialogTraditionPrint: false, //处方打印
      form: {
        tableList: [],
        curePrescriptionUse: {
          prescriptionId: "",
          usage: "",
          dailyDose: "",
          day: "",
          totalDose: "",
          frequency: "",
          getAddress: 1,
          id: ""
        }
      }
    };
  },
  created() {
    let th = this;
    th.hpId = th.adminUser.hpId;
  },
  mounted() {
    const th = this;
    th.deptName = th.$route.query.deptName;
    th.doctorName = th.$route.query.doctorName;
    th.professionalDeptName = th.$route.query.professionalDeptName;
  },
  methods: {
    onSubmit() {
      let th = this;
      let j = {};
      if (
        !th.form.curePrescriptionUse.prescriptionId &&
        th.form.tableList.length == 0
      )
        return;
      let curePrescription = {
        id: th.form.curePrescriptionUse.prescriptionId,
        cureId: th.cureId,
        hpId: th.hpId,
        patientId: th.patientId,
        deptId: th.deptId,
        doctorId: th.doctorId
      };
      let update = function() {
        th.btnLoading = true;
        th.$api
          .updatetraditionalMedicine(j)
          .then(res => {
            if (res.executed) {
              th.$message.success("操作成功");
              // th.$emit("success");
              for (let i = 0; i < res.data.length; i++) {
                let d = res.data[i];
                for (let g = 0; g < th.form.tableList.length; g++) {
                  let el = th.form.tableList[g];
                  if (!el.id) {
                    el.id = d;
                    break;
                  }
                }
              }
            } else {
              th.$message.error(res.message);
            }
            th.btnLoading = false;
            th.$nextTick(function() {
              th.$emit("submit");
              th.isOpenEdit = true;
            });
          })
          .catch(() => {
            th.btnLoading = false;
            th.isOpenEdit = true;
          });
      };
      let add = () => {
        th.btnLoading = true;
        th.$api
          .addMultipletraditionalMedicine(j)
          .then(res => {
            if (res.executed) {
              th.$message.success("操作成功");
              // th.$emit("success");
              for (let i = 0; i < res.data.length; i++) {
                let d = res.data[i];
                if (i == 0) continue;
                else if (i == 1) {
                  //处方ID
                  th.form.curePrescriptionUse.prescriptionId = d;
                } else if (i == res.data.length - 1) {
                  //获取用法ID
                  th.form.curePrescriptionUse.id = d;
                } else {
                  th.form.tableList[i - 2].id = d;
                }
              }
            } else {
              th.$message.error(res.message);
            }
            th.btnLoading = false;
            th.$nextTick(function() {
              th.$emit("submit");
              th.isOpenEdit = true;
            });
          })
          .catch(() => {
            th.btnLoading = false;
            th.isOpenEdit = true;
          });
      };
      th.$refs["form"].validate(v => {
        if (v) {
          th.isOpenEdit = false;
          let cureArr = [];
          //循环剔除不要的数据
          th.form.tableList.forEach(d => {
            let json = {};
            Object.assign(json, d);
            delete json.medicalDrugSale;
            delete json.inventory;
            cureArr.push(json);
          });
          j.curePrescriptionUse = JSON.stringify(th.form.curePrescriptionUse);
          j.curePrescriptionDrug = JSON.stringify(cureArr);
          j.curePrescription = JSON.stringify(curePrescription);
          if (th.form.curePrescriptionUse.prescriptionId) update();
          else add();
        }
      });
    },

    //删除项
    onDelItem(obj, index) {
      let th = this;
      // console.log(obj);
      if (obj.id) {
        let j = {
          prescriptionDrugId: obj.id
        };
        th.$api.prescriptionDrugpreDelete(j).then(res => {
          if (res.executed && res.data) {
            th.form.tableList.splice(index, 1);
          } else {
            th.$message.warning(res.message);
          }
        });
      } else {
        th.form.tableList.splice(index, 1);
      }
    },
    //保存模板
    onSaveTemplate() {
      let th = this;
      th.$refs["form"].validate(v => {
        if (v) {
          th.dialogSaveChinaDrugTemplate = true;
        }
      });
    },
    //添加药品进列表
    addFormList(json) {
      let th = this;
      //默认加上初始化的支付状态
      if (typeof json.payStatus == "undefined") {
        json.payStatus = 2;
      }
      if (typeof json.status == "undefined") {
        json.status = 0;
      }
      if (json.payStatus == 2 && json.status == 0) {
        //查找是否重复
        let data = th.form.tableList.find(d => {
          return d.drugId == json.drugId && d.payStatus == 2 && d.status == 0;
        });
        if (data) {
          return;
        }
        //判断库存
        if (json.payStatus == 2) {
          if (json.inventory && Object.keys(json.inventory).length > 0) {
            if (json.inventory.usableNum <= 0) {
              th.inventoryflaw(json);
              return;
            }
          } else {
            th.inventoryflaw(json);
            return;
          }
        }
        json.groupId = 0;
        th.form.tableList.push(json);
      } else {
        th.form.tableList.push(json);
      }
    },
    //判断是否可编辑
    toDisabled(obj) {
      if (obj.payStatus == 2 && obj.status == 0) {
        return false;
      } else {
        return true;
      }
    },
    //处理库存不足
    inventoryflaw(json) {
      const th = this;
      th.$message.warning(json.drugName + "库存不足");
      //判断list是否为空
      if (th.form.tableList.length == 0) {
        th.$emit("submit");
      }
    },
    //计算药品总量（单个药品）
    toCompute(obj) {
      let th = this;
      let value = 0;
      if (
        typeof th.form.curePrescriptionUse.day == "number" &&
        typeof obj.oneDose == "number" &&
        typeof th.form.curePrescriptionUse.dailyDose == "number"
      ) {
        let v =
          obj.oneDose *
          th.form.curePrescriptionUse.dailyDose *
          th.form.curePrescriptionUse.day;
        obj.useTotal = v;
        value = v;
      } else {
        obj.useTotal = 0;
      }
    },
    //计算总量(总)
    calculateTheTotal() {
      let th = this;
      let day = th.form.curePrescriptionUse.day;
      let dailyDose = th.form.curePrescriptionUse.dailyDose;
      if (day && dailyDose) {
        th.form.curePrescriptionUse.totalDose =
          Number.parseInt(day) * Number.parseInt(dailyDose);
      }
    }
    //处理库存不足
    // inventoryflaw(json) {
    //   const th = this;
    //   th.$message.warning(json.drugName + "库存不足");
    //   //判断list是否为空
    //   if (th.form.tableList.length == 0) {
    //     th.$emit("submit");
    //   }
    // }
  },
  watch: {
    selectTemplateData: {
      deep: true,
      handler: function(n) {
        let th = this;
        let data1 = n.traditionalMedicineDrugTemplateMedicalAdviceDTO;
        th.form.curePrescriptionUse = {
          prescriptionId: "",
          usage: data1.usage,
          dailyDose: "",
          day: data1.day,
          totalDose: data1.total,
          frequency: data1.frequency,
          getAddress: data1.takeMedicinePlace,
          id: ""
        };
        n.traditionalMedicineDrugTemplateMedicalAdviceItemDTOS.forEach(item => {
          // console.log(item);
          let j = {
            drugName: item.adviceName,
            sellMoney: "",
            prescriptionId: "",
            hpId: th.adminUser.hpId,
            patientId: th.patientId,
            deptId: th.adminUser.hpId,
            doctorId: th.doctorId,
            drugId: item.id,
            groupId: 0,
            oneDose: item.timesDosage,
            oneDoseUnit: item.timesUnit,
            use: "",
            frequency: item.frequency,
            useDay: "",
            useTotal: "",
            status: item.status,
            totalUnit: item.timesUnit,
            getAddress: "",
            id: "",
            remark: item.desc,
            inventory: item.inventoryStatisticVO
              ? item.inventoryStatisticVO
              : {}
          };
          th.addFormList(j);
        });
      }
    },
    form: {
      deep: true,
      handler: function(n, o) {
        let th = this;
        //计算数量
        n.tableList.forEach(item => {
          th.toCompute(item);
        });
        th.calculateTheTotal();
        if (!th.isOpenEdit) return;
        if (
          n.tableList.length == 0 &&
          !th.form.curePrescriptionUse.prescriptionId
        ) {
          th.$emit("submit");
        } else {
          th.$emit("change");
        }
      }
    },
    //渲染初始值
    initData: {
      deep: true,
      immediate: true,
      handler: function(n) {
        let th = this;
        if (!n) {
          th.isOpenEdit = true;
          return;
        }
        let fn = function() {
          if (
            n.curePrescriptionDrugInfos &&
            n.curePrescriptionDrugInfos.length > 0
          )
            th.form.tableList = n.curePrescriptionDrugInfos;
          if (n.curePrescriptionUseInfo) {
            th.form.curePrescriptionUse = n.curePrescriptionUseInfo;
          }
          th.$nextTick(function() {
            th.isOpenEdit = true;
          });
        };
        let time = setInterval(function() {
          if (th.getAddressArr.length > 0) {
            clearInterval(time);
            fn();
          }
        }, 300);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.el-form-item {
  margin-bottom: 0;
}
</style>